import React, { useState, memo, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Carousel,
  Radio,
  Tag,
  Tooltip,
  Button,
  Card,
  Row,
  Col,
  Divider,
  Space,
  Badge,
  Rate,
  message,
} from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { setStrategyType, getStrategyType  } from '@/utils/keyTypeStore'
import {
  StarFilled,
  StarOutlined,
  QuestionCircleOutlined,
  KeyOutlined,
  SortAscendingOutlined,
  CloseOutlined,
  BookOutlined,
  ShoppingCartOutlined,
  DashboardOutlined,
  DesktopOutlined,
  RightOutlined,
  TrophyOutlined,
  FileOutlined,
  TagsOutlined,
  MenuOutlined,
  CheckOutlined,
  ArrowRightOutlined,
} from '@ant-design/icons';
import './index.scss';

function Home() {
  const navigate = useNavigate();
  const bookState = useSelector(state => state.book);

  const showcaseItems = [
    { icon: <BookOutlined />, name: '图书管理' },
    { icon: <ShoppingCartOutlined />, name: '电商功能' },
    { icon: <DashboardOutlined />, name: '系统核心' },
    { icon: <DesktopOutlined />, name: '数据分析' },
  ];

  const [currentStrategy, setCurrentStrategy] = useState('id');
  

  const handleStrategyChange = e => {
    const type = e.target.value
    message.success({
      content: `已切换到${type}`,
    });
    setStrategyType(type)
    setCurrentStrategy(type);
  
  };

  useEffect(() => {
    setStrategyType('id')
  }, [])

  const getStrategyTagType = () => {
    const typeMap = {
      id: 'processing',
      index: 'success',
      none: 'default',
    };
    return typeMap[currentStrategy] || 'processing';
  };

  const getStrategyIcon = () => {
    const iconMap = {
      id: <KeyOutlined />,
      index: <SortAscendingOutlined />,
      none: <CloseOutlined />,
    };
    return iconMap[currentStrategy] || <KeyOutlined />;
  };

  const getStrategyDescription = () => {
    const descMap = {
      id: '使用数据项的唯一标识符作为key，这是React推荐的做法，可以最大程度地提高列表渲染性能。',
      index:
        '使用数组索引作为key，适用于静态列表，但在数据频繁变动时可能影响性能。',
      none: '不使用key或使用索引作为key，这种方式在某些场景下可能导致不必要的DOM重新渲染。',
    };
    return descMap[currentStrategy] || descMap.id;
  };

  const getStrategyText = strategy => {
    const texts = {
      id: '使用ID作为Key',
      index: '使用索引作为Key',
      none: '不使用Key',
    };
    return texts[strategy] || '未知策略';
  };

  const bookList = useMemo(() => {
    return [...bookState.books].sort((a, b) => b.sales - a.sales).slice(0, 8);
  }, [bookState.books]);

  const viewAll = () => {
    navigate('/books');
  };
  const viewBookDetail = book => {
    sessionStorage.setItem('BOOK', JSON.stringify(book))
    navigate(`/book/${book.id}`);
  };

  return (
    <div className='home-page'>
      <h1 className='page-heading'>图书馆电商管理系统</h1>

      <div className='carousel-section'>
        <Carousel autoplay effect='fade' className='system-carousel'>
          <div className='carousel-slide slide-overview'>
            <div className='slide-content'>
              <div className='slide-text'>
                <div className='slide-badge'>
                  <Badge
                    count={<StarFilled />}
                    style={{ backgroundColor: '#1890ff', color: 'white' }}
                  />
                  <span>智慧图书馆</span>
                </div>
                <h2>现代化电商管理平台</h2>
                <div className='slide-features'>
                  <div className='feature-tag'>
                    <DashboardOutlined />
                    <span>高性能架构</span>
                  </div>
                  <div className='feature-tag'>
                    <DesktopOutlined />
                    <span>大数据支持</span>
                  </div>
                  <div className='feature-tag'>
                    <ShoppingCartOutlined />
                    <span>响应式设计</span>
                  </div>
                </div>
              </div>
              <div className='slide-visual'>
                <div className='visual-icon main-icon'>
                  <BookOutlined />
                </div>
                <div className='floating-elements'>
                  <div className='floating-item' style={{ '--delay': '0s' }}>
                    <FileOutlined />
                  </div>
                  <div className='floating-item' style={{ '--delay': '0.5s' }}>
                    <ShoppingCartOutlined />
                  </div>
                  <div className='floating-item' style={{ '--delay': '1s' }}>
                    <TagsOutlined />
                  </div>
                  <div className='floating-item' style={{ '--delay': '1.5s' }}>
                    <MenuOutlined />
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className='carousel-slide slide-features'>
            <div className='slide-content'>
              <div className='slide-text'>
                <div className='slide-badge'>
                  <Badge
                    count={<DashboardOutlined />}
                    style={{ backgroundColor: '#1890ff', color: 'white' }}
                  />
                  <span>核心功能</span>
                </div>
                <h2>四大管理模块</h2>
                <div className='module-grid'>
                  <div
                    className='module-item'
                    onClick={() => history.push('/books')}
                  >
                    <FileOutlined />
                    <span>图书目录</span>
                  </div>
                  <div
                    className='module-item'
                    onClick={() => history.push('/dynamic-medium-list')}
                  >
                    <SortAscendingOutlined />
                    <span>库存管理</span>
                  </div>
                  <div
                    className='module-item'
                    onClick={() => history.push('/order-process')}
                  >
                    <DesktopOutlined />
                    <span>订单处理</span>
                  </div>
                  <div
                    className='module-item'
                    onClick={() => history.push('/book-catalog')}
                  >
                    <MenuOutlined />
                    <span>分类管理</span>
                  </div>
                </div>
              </div>
              <div className='slide-visual'>
                <div className='feature-showcase'>
                  {showcaseItems.map((item, index) => (
                    <div
                      className='showcase-item'
                      key={index}
                      style={{ animationDelay: `${index * 0.3}s` }}
                    >
                      {item.icon}
                      <span>{item.name}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          <div className='carousel-slide slide-tech'>
            <div className='slide-content'>
              <div className='slide-text'>
                <div className='slide-badge'>
                  <Badge
                    count={<DashboardOutlined />}
                    style={{ backgroundColor: '#1890ff', color: 'white' }}
                  />
                  <span>技术优势</span>
                </div>
                <h2>React性能优化</h2>
                <div className='tech-stats'>
                  <div className='stat-item'>
                    <div className='stat-number'>3种</div>
                    <div className='stat-label'>Key策略</div>
                  </div>
                  <div className='stat-item'>
                    <div className='stat-number'>1000+</div>
                    <div className='stat-label'>并发支持</div>
                  </div>
                  <div className='stat-item'>
                    <div className='stat-number'>99%</div>
                    <div className='stat-label'>性能优化</div>
                  </div>
                </div>
              </div>
              <div className='slide-visual'>
                <div className='tech-visual'>
                  <div className='code-window'>
                    <div className='window-header'>
                      <div className='window-dots'>
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                      <span className='window-title'>performance.js</span>
                    </div>
                    <div className='window-content'>
                      <div className='code-line'>
                        <span className='keyword'>const</span>
                        <span className='variable'>strategy</span> =
                        <span className='string'>'{currentStrategy}'</span>
                      </div>
                      <div className='code-line'>
                        <span className='keyword'>if</span>
                        <span className='bracket'>(</span>
                        <span className='variable'>strategy</span>
                        <span className='operator'>===</span>
                        <span className='string'>'id'</span>
                        <span className='bracket'>)</span>
                      </div>
                      <div className='code-line indent'>
                        <span className='keyword'>return</span>
                        <span className='variable'>item.id</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className='carousel-slide slide-cta'>
            <div className='slide-content'>
              <div className='slide-text'>
                <div className='slide-badge'>
                  <Badge
                    count={<TrophyOutlined />}
                    style={{ backgroundColor: '#1890ff', color: 'white' }}
                  />
                  <span>立即体验</span>
                </div>
                <h2>开始体验</h2>
                <div className='cta-buttons'>
                  <Button
                    type='primary'
                    className='cta-button warning'
                    onClick={() => history.push('/books')}
                  >
                    <FileOutlined />
                    <span>图书目录</span>
                  </Button>
                  <Button
                    type='primary'
                    className='cta-button primary'
                    onClick={() => history.push('/book-catalog')}
                  >
                    <MenuOutlined />
                    <span>分类管理</span>
                  </Button>
                  <Button
                    type='primary'
                    className='cta-button success'
                    onClick={() => history.push('/order-process')}
                  >
                    <TagsOutlined />
                    <span>订单中心</span>
                  </Button>
                </div>
              </div>
              <div className='slide-visual'>
                <div className='cta-visual'>
                  <div className='rocket-container'>
                    <div className='rocket'>
                      <TrophyOutlined />
                    </div>
                    <div className='stars'>
                      {[1, 2, 3, 4, 5].map(i => (
                        <div
                          className='star'
                          key={i}
                          style={{ animationDelay: `${i * 0.2}s` }}
                        >
                          ✨
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Carousel>
      </div>

      <div className='key-strategy-section'>
        <div className='section-header'>
          <h3>
            <KeyOutlined />
            Key 策略选择
          </h3>
          <Tooltip title='不同的Key策略会影响React列表渲染的性能表现'>
            <QuestionCircleOutlined className='help-icon' />
          </Tooltip>
        </div>

        <div className='strategy-card'>
          <div className='strategy-options'>
            <Radio.Group
              onChange={handleStrategyChange}
              value={currentStrategy}
              className='strategy-radio-group flex flex-col gap-4'
            >
              <Radio value='id' className='bg-white rounded-xl p-4 flex w-full'>
                <div className='radio-content'>
                  <KeyOutlined />
                  <div className='radio-text'>
                    <span className='primary-text'>使用ID</span>
                    <span className='secondary-text'>
                      使用数据的唯一标识作为key
                    </span>
                  </div>
                </div>
              </Radio>

              <Radio
                value='index'
                className='bg-white rounded-xl p-4 flex w-full'
              >
                <div className='radio-content'>
                  <SortAscendingOutlined />
                  <div className='radio-text'>
                    <span className='primary-text'>使用索引</span>
                    <span className='secondary-text'>使用数组索引作为key</span>
                  </div>
                </div>
              </Radio>

              <Radio
                value='none'
                className='bg-white rounded-xl p-4 flex w-full'
              >
                <div className='radio-content'>
                  <CloseOutlined />
                  <div className='radio-text'>
                    <span className='primary-text'>不使用key</span>
                    <span className='secondary-text'>
                      默认模式，可能影响性能
                    </span>
                  </div>
                </div>
              </Radio>
            </Radio.Group>
          </div>

          <div className='current-strategy'>
            <div className='strategy-tag'>
              <Tag
                color={getStrategyTagType()}
                icon={getStrategyIcon()}
                className='strategy-tag'
              >
                {getStrategyText(currentStrategy)}
              </Tag>
            </div>
            <div className='strategy-description'>
              {getStrategyDescription()}
            </div>
          </div>
        </div>
      </div>

      <Row gutter={[16, 16]} className='function-cards'>
        <Col sm={24} lg={12}>
          <Card  hoverable className='function-card'>
            <div className='card-header'>
              <div className='card-icon'>
                <BookOutlined style={{ color: 'white', fontSize: '1.75rem' }} />
              </div>
              <div className='flex-1 flex items-center gap-1'>
                <Tag color='blue'>基础功能</Tag>
                <h3>图书管理</h3>
              </div>
            </div>
            <p className='card-desc'>
              支持海量图书数据的高效管理，包括图书信息维护、库存跟踪、分类管理等功能。
            </p>
            <ul className='feature-list'>
              <li>
                <CheckOutlined /> 图书信息维护
              </li>
              <li>
                <CheckOutlined /> 库存跟踪
              </li>
              <li>
                <CheckOutlined /> 分类管理
              </li>
            </ul>
          </Card>
        </Col>

        <Col sm={24} lg={12}>
          <Card  hoverable className='function-card'>
            <div className='card-header'>
              <div className='card-icon'>
                <ShoppingCartOutlined
                  style={{ color: 'white', fontSize: '1.75rem' }}
                />
              </div>
              <div className='flex-1 flex items-center gap-1'>
                <Tag color='orange'>电商功能</Tag>
                <h3>电商系统</h3>
              </div>
            </div>
            <p className='card-desc'>
              完整的电商交易流程，支持在线下单、支付处理、订单跟踪、用户管理等。
            </p>
            <ul className='feature-list'>
              <li>
                <CheckOutlined /> 在线下单
              </li>
              <li>
                <CheckOutlined /> 支付处理
              </li>
              <li>
                <CheckOutlined /> 订单跟踪
              </li>
            </ul>
          </Card>
        </Col>

        <Col sm={24} lg={12}>
          <Card  hoverable className='function-card'>
            <div className='card-header'>
              <div className='card-icon'>
                <DashboardOutlined
                  style={{ color: 'white', fontSize: '1.75rem' }}
                />
              </div>
              <div className='flex-1 flex items-center gap-1'>
                <Tag color='purple'>核心功能</Tag>
                <h3>系统核心</h3>
              </div>
            </div>
            <p className='card-desc'>
              系统核心功能模块，提供强大的业务支持和数据处理能力。
            </p>
            <ul className='feature-list'>
              <li>
                <CheckOutlined /> 数据处理
              </li>
              <li>
                <CheckOutlined /> 业务流程
              </li>
              <li>
                <CheckOutlined /> 系统集成
              </li>
            </ul>
          </Card>
        </Col>

        <Col sm={24} lg={12}>
          <Card  hoverable className='function-card'>
            <div className='card-header'>
              <div className='card-icon'>
                <DesktopOutlined
                  style={{ color: 'white', fontSize: '1.75rem' }}
                />
              </div>
              <div className='flex-1 flex items-center gap-1'>
                <Tag color='cyan'>高级特性</Tag>
                <h3>性能优化</h3>
              </div>
            </div>
            <p className='card-desc'>
              采用React最佳实践，支持多种Key绑定策略，确保大数据量场景下的流畅体验。
            </p>
            <ul className='feature-list'>
              <li>
                <CheckOutlined /> Key策略优化
              </li>
              <li>
                <CheckOutlined /> 性能监控
              </li>
              <li>
                <CheckOutlined /> 大数据处理
              </li>
            </ul>
          </Card>
        </Col>
      </Row>

      <div className='book-section'>
        <div className='section-header'>
          <h2>热门图书</h2>
          <div className='section-actions'>
            <Button type='link' onClick={viewAll}>
              查看全部 <ArrowRightOutlined />
            </Button>
          </div>
        </div>

        <Row gutter={[16, 16]}>
          {bookList.map(book => (
            <Col xs={24} sm={12} md={8} lg={6} key={book.id}>
              <Card
                hoverable
                className='book-card'
                onClick={() => viewBookDetail(book)}
                cover={
                  <div className='book-cover'>
                    <img
                      src={book.coverUrl || '/images/book-placeholder.png'}
                      alt={book.title}
                      onError={e => {
                        e.target.src = '/images/book-placeholder.png';
                      }}
                    />
                    <div className='book-hover'>
                      <Button type='primary' shape='round' size='small'>
                        查看详情
                      </Button>
                    </div>
                  </div>
                }
              >
                <div className='book-info'>
                  <h3>{book.title}</h3>
                  <div className='book-meta'>
                    <span className='book-author'>{book.author}</span>
                    <Tag color='blue' className='book-category'>
                      {book.category}
                    </Tag>
                  </div>
                  <div className='book-rating'>
                    <Rate disabled allowHalf defaultValue={book.rating} />

                    <span className='rating-value'>{book.rating}</span>
                  </div>

                  <div className='book-footer'>
                    <span className='book-price'>¥{book.price}</span>
                    <span className='book-sales'>销量 {book.sales}</span>
                  </div>
                </div>
              </Card>
            </Col>
          ))}
        </Row>
      </div>
    </div>
  );
}

export default memo(Home);
